<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOM Move Demo</title>
    <style>
        .container {
            border: 2px solid #333;
            padding: 10px;
            margin: 10px;
            min-height: 50px;
        }

        .container1 {
            background-color: #f0f0f0;
        }

        .container2 {
            background-color: #e0e0ff;
        }

        .item {
            background-color: #ffcccc;
            padding: 5px;
            border-radius: 3px;
        }
    </style>
</head>

<body>
    <h2>DOM insertBefore 移动演示</h2>


    <!-- 容器1，初始包含可移动元素 -->
    <div class="container container1" id="container1">
        <h3>容器1</h3>
        <div class="item" id="movable-item">可移动元素</div>
    </div>

    <!-- 容器2，初始为空 -->
    <div class="container container2" id="container2">
        <h3>容器2</h3>
    </div>

    <!-- 按钮用于触发元素移动和重置 -->
    <button onclick="moveElement()">移动元素到容器2</button>
    <button onclick="resetElement()">重置</button>

    <script>
        /**
         * 将元素从容器1移动到容器2
         */
        function moveElement() {
            const item = document.getElementById('movable-item');
            const container2 = document.getElementById('container2');

            console.log('移动前:');
            console.log('容器1子元素数量:', document.getElementById('container1').children.length);
            console.log('容器2子元素数量:', container2.children.length);

            // 使用 insertBefore 将元素移动到容器2
            container2.insertBefore(item, null);

            console.log('移动后:');
            console.log('容器1子元素数量:', document.getElementById('container1').children.length);
            console.log('容器2子元素数量:', container2.children.length);
        }

        /**
         * 重置元素位置，将其移回容器1
         */
        function resetElement() {
            const item = document.getElementById('movable-item');
            const container1 = document.getElementById('container1');
            container1.appendChild(item);
        }
    </script>
</body>

</html>